﻿using System.Collections.Generic;
using System.Linq;
using Metro.Kashikoi.Common.ExceptionHandling;
using Metro.Kashikoi.Service.Common.Entity;
using Metro.Kashikoi.Service.Item.Entity;
using Metro.Kashikoi.ServiceContract.Item;

namespace Metro.Kashikoi.Service.Item.Business
{
    /// <summary>
    /// This class implements the interface <c>ICategoryFacade</c>.
    /// </summary>
    class CategoryFacade : ICategoryFacade
    {
        public void CreateCategory(IUnitOfWork context, ColorCategory category)
        {
            var rep = new Repository<Category>(context);

            CheckDuplicate(rep, category);
            category.Deleted = false;
            rep.Add(category);
        }

        public void UpdateCategory(IUnitOfWork context, ColorCategory category)
        {
            var rep = new Repository<Category>(context);

            var entity = rep.GetCategory(category.Id);
            if (category.Name != entity.Name)
            {
                CheckDuplicate(rep, category);
                entity.Name = category.Name;
            }
        }

        public void DeleteCategory(IUnitOfWork context, int categoryId)
        {
            var rep = new Repository<Category>(context);

            var entity = rep.GetCategory(categoryId);
            entity.Deleted = true;
        }

        public ColorCategory GetCategory(IUnitOfWork context, int id)
        {
            var rep = new Repository<Category>(context);

            return rep.GetCategory(id);
        }

        public IList<ColorCategory> GetAllCategories(IUnitOfWork context)
        {
            var rep = new Repository<Category>(context);

            return rep.Where<ColorCategory>(o => o.Deleted == false).ToList();
        }

        #region Private Methods

        private void CheckDuplicate(Repository<Category> rep, Category entity)
        {
            if (rep.Count(o => o.Name == entity.Name && o.Deleted == false) > 0)
            {
                throw new AppException(string.Format(
                    "Duplicate category {0} found.", entity.Name));
            }
        }

        #endregion
    }
}
